<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Api\MiniProgramController;
use App\Http\Controllers\Controller;
use App\Models\Message;
use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Response;
use Yansongda\LaravelPay\Facades\Pay;

class OrderController extends Controller
{
    function index() {
        return view('admin.order.index');
    }

    /**
     * 订单数据接口
     * @param Request $request
     * @return JsonResponse
     */
    public function data(Request $request) {
        $model = Order::query();
        if ($mobile = $request->get('mobile')){
            $model->where('mobile',$mobile);
        }
        if ($start_time = $request->get('start_time')){
            $model->where('created_at','>=',$start_time);
        }
        if ($end_time = $request->get('end_time')){
            $model->where('created_at','<=',$end_time);
        }
        if ($status = $request->get('status')){
            $model->where('status','=',$status);
        }

        $res = $model->with([
            'user' => function($query) {
                return $query->select('id','mobile');
            },
            'address' => function($query) {
                return $query->select('id','district','detail','consignee','consignee_mobile');
            }
        ])->orderBy('id','desc')->paginate($request->get('limit',30));

        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res->total(),
            'data'  => $res->items(),
        ];
        return Response::json($data);
    }

    //修改订单快递单号。只有待发货的才可以
    function delivery(Request $request) {
        $request->validate([
            'id'         =>  'exists:orders',
            'delivery'  =>  'required'
        ]);
        $result = Order::where(['id' =>$request->post('id'), 'status' => TO_DELIVERY])
                ->update([
                    'delivery'  => $request->post('delivery'),
                    'status'    => TO_SIGN
                ]);
        if ($result) {
            $data = [
                'code' => 0,
                'msg'   => '修改快递单号成功，等待客户收货',
            ];
        }else {
            $data = [
                'code' => 1,
                'msg'   => '修改快递单号失败',
            ];
        }
        return Response::json($data);
    }

    //订单详情
    function detail($id) {
        if ($order = Redis::get('order_detail_' . $id)) {
            return unserialize($order);
        }
        $order = Order::with(['sku'=>function($query){
            return $query->select('id','title');
        },'product'=>function($query){
            return $query->select('id','title','p_rate','p_p_rate');
        },'rebates'=>function($query) {
            return $query->join('users','users.id','=','rebates.user_id')->select('rebates.id','level','order_id','money','users.mobile');
        }])->find($id);

        Redis::set('order_detail_' . $id,serialize($order));

        //查询订单的分润
        return $order;
    }

    //查询订单支付状态
    function payment_query($no) {
        $mp_controller = new MiniProgramController();
        $query_result = $mp_controller->payment_query($no);
        return $this->response(0,$query_result);
    }

    /**
     * @param $order_no
     * @throws \Yansongda\Pay\Exceptions\GatewayException
     * @throws \Yansongda\Pay\Exceptions\InvalidArgumentException
     * @throws \Yansongda\Pay\Exceptions\InvalidSignException
     * 退款申请
     *
     */
    public function refundOrder(Request $request){
        $order = Order::where(['no'=>$request->order_no,'status'=>2])->first();
        if(!$order) {
            return ['data'=>null,'message'=>'操作失败','code'=>0];
        }
        $out_refund_no = "T" . date('YmdHis');
        $config = config('pay.wechat');
        $result = \Yansongda\LaravelPay\Facades\Pay::wechat($config)->refund([
            'out_trade_no' => $request->order_no, // 之前的订单流水号
            'total_fee' => $order->cash_money * 100,   //原订单金额，单位分
            'refund_fee' => $order->cash_money * 100,  // 要退款的订单金额，单位分
            'out_refund_no' => $out_refund_no, // 退款订单号
            'notify_url' => config('app.url') . '/refund/notify' //
        ]);
        $order->status = 5;
        $order->refund_no = $out_refund_no;
        $order->reason = '后台操作退单';
        $order->save();
        Message::create(['order_id'=>$order->id,'status'=>0,'type'=>'refund']);
        return ['data'=>$result,'message'=>'操作成功','code'=>200];
    }


}
